package niit.wei.service.impl;

import niit.wei.service.RegisterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @Author WeiJinLong
 * @Date 2023-08-16 20:15
 * @Version 1.0
 */
@Service
public class RegisterServiceImpl implements RegisterService {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public Object veiFiCodeByNumber(Integer phoneNumber, String addr) {
        Random random = new Random();
        int veiFiCode = random.nextInt(9000) + 1000;
        String keyCode = "phone:code";
        String keyCacheIp = "ip:cache:" + addr;
        if (!addr.equals(redisTemplate.opsForValue().get(keyCacheIp))) {
            redisTemplate.opsForValue().set(keyCode, veiFiCode, 60, TimeUnit.SECONDS);
            redisTemplate.opsForValue().increment(keyCacheIp);
            Integer o = (Integer) redisTemplate.opsForValue().get(keyCacheIp);
            if (o > 3) {
                redisTemplate.opsForValue().set(keyCacheIp, addr, 12, TimeUnit.HOURS);
                return "频繁发送ip已被锁定！";
            }
        } else {
            return "该ip已锁定，剩余时间" + redisTemplate.getExpire(keyCacheIp) / 60 / 60 + "小时";
        }
        return veiFiCode;
    }
}
